package org.yfl.mbg.enhance.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * 基于jackson的json解析工具类
 * @author yanfeilin
 * @version 1.0.0
 * @date 2020/6/3 22:59
 */
public class JsonUtil {

    private JsonUtil(){

    }

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 对象序列化成json字符串
     * @param object
     * @return
     */
    public static String obj2string(Object object){
        String result = "";
        try {
            result = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
                e.printStackTrace();
        }
        return result;
    }

    /**
     * json字符串转换为java对象
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T jsonString2obj(String jsonStr,Class<T> clazz){
        T resObj = null;
        try {
            resObj = objectMapper.readValue(jsonStr, clazz);
        }catch (IOException e){
            e.printStackTrace();
        }
        return resObj;
    }
}
